package com.xf.protocol;

import com.xf.common.Invocation;
import com.xf.rigister.RemoteRigister;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServerHandler_pro_rig implements Runnable{
    private ServerSocket serverSocket;
    public HttpServerHandler_pro_rig(ServerSocket serverSocket) {
        this.serverSocket=serverSocket;
    }

    public void run() {
        //System.out.println("New pro connected");
        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            System.out.println("接收服务端请求时发生异常！");
        }
        ObjectInputStream inputStream = null;
        // Read the request line
        Invocation invocation = null;
        try {
            inputStream = new ObjectInputStream(clientSocket.getInputStream());
            Object o = inputStream.readObject();
            if(o instanceof Invocation){
                System.out.println("收到服务端注册请求");
                String SerAddress=(String)inputStream.readObject();
                Integer port = (Integer) inputStream.readObject();
                handle_invocation((Invocation)o,SerAddress,port);
            }

            inputStream.close();
            clientSocket.close();
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("读取服务端信息时发生异常");
        }
    }

    //处理注册信息
    private void handle_invocation(Invocation invocation,String ServerAddress,Integer port){
        boolean found=RemoteRigister.Isservice_exist(invocation,ServerAddress,port);
        if(!found){
            RemoteRigister.rigist(invocation,ServerAddress,port);
            System.out.println("服务注册成功！");
        }
        else {
            System.out.println("The Service "+invocation.getInterfaceName()+invocation.getVersion()+":"+invocation.getMethodName()+" have been registed");
        }

    }


}
